<?php 

class QpidBalance {
	
	/**
	 * 获得用于列表每个月佣金的 DataProvider 对象
	 * @param string $owner_id 加盟账户 
	 * @param string $program 指定佣金模式。若不指定此参数，则自动选择佣金较多的模式
	 */
	public static function getDataProvider($owner_id, $program=null) {
		if (empty($program)) {
			$result = QpidBalance::activeCount($owner_id);
			$program = $result['program'];
		}
		return QpidBalanceDataProvider::$program($owner_id);
	}
	
	/**
	 * 实时计算加盟账号所得的佣金
	 * 在计算佣金时，按不同的佣金模式进行计算比较，选择佣金较多的一种模式作为计算结果
	 * @param string $owner_id
	 * @return 返回佣金金额和佣金模式
	 */
	public static function activeCount($owner_id) {
		$params = array(':owner_id' => $owner_id);
		$userCount = User::model()->count('owner_id=:owner_id AND accept="Y" AND payment_status=0', $params);
		$userCommission = QpidBalance::countPerLead(Yii::app()->user->id, $userCount);
		
		$sql = "SELECT sum(amount) 
				FROM first_order f, order_history o 
				WHERE f.order_id=o.order_id 
				AND owner_id='$owner_id' 
				AND verify_status=1
				AND payment_status=0";
		$orderAmount = Yii::app()->db->createCommand($sql)->queryScalar();
		$firstOrderCommission = QpidBalance::countPerFirstOrder($orderAmount, $userCount);
		
		$balance = max($userCommission, $firstOrderCommission);
		$program = ($userCommission>$firstOrderCommission) ? 'perLead' : 'perFirstOrder';
		
		return array('balance' => $balance, 'program' => $program);
	}
	
	/**
	 * 按首次订单总额、注册会员数计算佣金
	 * @param float $order_amount 未支付佣金的首次订单总额
	 * @param int $member_count 未支付佣金的注册会员数
	 */
	public static function countPerFirstOrder($orderAmount, $userCount) {
		$conf = Yii::app()->params['paymentRates']['perFirstOrder'];
		return $orderAmount * $conf['order'] + $conf['lead'] * $userCount;
	}
	
	/**
	 * 按会员注册数计算佣金
	 * @param string $owner_id 加盟账号
	 * @param int $count 未支付佣金的注册会员数
	 */
	public static function countPerLead($owner_id, $count) {
		$totalCount = User::model()->count("owner_id=:owner_id AND accept='Y'", array(':owner_id' => $owner_id));
		$totalCount = 65;
		$amount = 0;
		$conf = Yii::app()->params['paymentRates']['perLead'];
		if ($totalCount > $conf[1][2]) {
			$c5 = $totalCount - $conf[1][2];
			if ($count < $c5) {
				$c5 = $count;
			}
			$count -= $c5;
			$totalCount -= $c5;
			$amount += $c5 * $conf[2][0];
		}
		if ($count > 0 && $totalCount > $conf[0][2]) {
			$c4 = $totalCount - $conf[0][2];
			if ($count < $c4) {
				$c4 = $count;
			}
			$count -= $c4;
			$totalCount -= $c4;
			$amount += $c4 * $conf[0][0];
		}
		if ($count > 0) {
			$amount += $count * $conf[0][0];
		}
		
		return $amount;
	}
}
